/**
 * 快递
 */

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import { Button, message, Modal } from 'antd';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';
import moment from 'moment';

import {
  pkgExpressOrderPage,
  pkgExpressOrderDetail,
  delPkgExpressOrder
} from '../service';
import {
  Const
} from '../../Const';

import AuthComponent from '@/components/Authorized/AuthComponent';
import AddEditExpress from '../components/AddEditExpress';

class PrivateData {
  static toolBarRenderArr = [
    { text: '新增', value: '1', authCode: 'basicPermissions' },
    { text: '修改', value: '2', authCode: 'basicPermissions' },
    { text: '删除', value: '3', authCode: 'basicPermissions' },
    { text: '查看详情', value: '4', authCode: 'basicPermissions' },
  ];
}

const ExpressInfo = props => {

  const { modalVisible, onCancel, onSubmit, itemData, ownerType } = props;

  const actionRef = useRef();
  const ref = useRef();

  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 勾选索引
  const [selectedRows, setSelectedRows] = useState([]); // 勾选列

  const [addEditExpressVisible, setAddEditExpressVisible] = useState(false); // 新增修改弹窗
  const [addEditExpressType, setAddEditExpressType] = useState('add');
  const [detailData, setDetailData] = useState({}); // 详情

  useEffect(() => {
    if (modalVisible) {
      setSelectedRowKeys([]);
      setSelectedRows([]);
    }
  }, [modalVisible]);

  // rowSelection
  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys);
    setSelectedRows(selectedRows);
  };
  const rowSelection = {
    type: 'radio',
    selectedRowKeys,
    onChange: tableSelectChange,
  };

  // 新增编辑 - 打开
  const addEditExpressOpen = useCallback(type => {
    if (type) setAddEditExpressType(type);
    setAddEditExpressVisible(true);
  }, []);
  // 新增编辑 - 取消
  const addEditExpressCancel = useCallback(() => {
    setAddEditExpressVisible(false);
  }, []);
  // 新增编辑 - 提交
  const addEditExpressSubmit = useCallback(() => {
    setAddEditExpressVisible(false);
    actionRef.current.reload();
  }, []);

  // 快递单详情
  const { run: runPkgExpressOrderDetail } = useRequest(params => pkgExpressOrderDetail(params), {
    manual: true,
    onSuccess (res) {
      console.log(res, '快递单详情');
      let data = res || {};
      setDetailData(data);
      addEditExpressOpen();
    }
  });

  // 删除快递单
  const { run: runDelPkgExpressOrder } = useRequest(data => delPkgExpressOrder(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '删除快递单');
      setSelectedRowKeys([]);
      setSelectedRows([]);
      actionRef.current.reload();
    }
  })

  // 顶部点击事件
  const headerTitleClick = useCallback(val => {
    if (val === '1') {
      setAddEditExpressType('add');
      setDetailData({});
      addEditExpressOpen('add');
    } else {
      if (selectedRows.length !== 1) {
        message.warning('请勾选一条数据');
        return;
      }
    }
    if (val === '2' && selectedRows.length === 1) {
      setAddEditExpressType('edit');
      if (selectedRows[0].expressOrderId) {
        runPkgExpressOrderDetail({
          // expressOrderId: selectedRows[0].expressOrderId
          ids: [selectedRows[0].id]
        });
      } else {
        message.warning('未获取到快递单号');
      }
    }
    if (val === '3' && selectedRows.length === 1) {
      Modal.confirm({
        title: '确认删除',
        content: '删除该条记录？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          runDelPkgExpressOrder({
            accidentId: selectedRows[0].accidentId,
            ids: [selectedRows[0].id]
          });
        }
      });
    }
    if (val === '4' && selectedRows.length === 1) {
      setAddEditExpressType('view');
      if (selectedRows[0].expressOrderId) {
        runPkgExpressOrderDetail({
          ids: [selectedRows[0].id]
        })
      } else {
        message.warning('未获取到快递单号');
      }
    }
  }, [selectedRows]);

  const okHandle = useCallback(() => {
    onCancel();
  }, []);

  const columns = [
    {
      title: '快递单号',
      dataIndex: 'expressOrderId',
      width: 200,
      hideInSearch: true,
    },
    // {
    //   title: '运送费',
    //   dataIndex: 'expressPrice',
    //   width: 100,
    //   hideInSearch: true,
    // },
    {
      title: '收件人',
      dataIndex: 'expressRecipient',
      width: 180,
      hideInSearch: true,
    },
    {
      title: '收件人电话1',
      dataIndex: 'recipientPhoneFirst',
      width: 200,
      hideInSearch: true,
    },
    {
      title: '收件人电话2',
      dataIndex: 'recipientPhoneSecond',
      width: 200,
      hideInSearch: true,
    },
    {
      title: '快递时间',
      dataIndex: 'expressDate',
      width: 200,
      hideInSearch: true,
    },
    {
      title: '快递单录入时间',
      dataIndex: 'createTime',
      width: 200,
      hideInSearch: true,
    },
    {
      title: '行李号',
      dataIndex: 'pkgNo',
      width: 200,
      hideInSearch: true,
    },
  ];

  return (
    <Modal
      destroyOnClose
      title="快递"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={onCancel}
      width={800}
      maskClosable={false}
    >
      <>
        <ProTable
          actionRef={actionRef}
          formRef={ref}
          className={styles.compactTable}
          rowKey="id"
          rowSelection={rowSelection}
          headerTitle="快递单列表"
          toolBarRender={() => PrivateData.toolBarRenderArr.map((item, index) => (
            <AuthComponent authCode={Const.permissionsType.get(+ownerType) + '.' + item.authCode} key={index}>
              <Button
                type="primary"
                onClick={() => headerTitleClick(item.value)}>
                {item.text}
              </Button>
            </AuthComponent>
          ))}
          request={params => {
            params.accidentId = itemData.accidentId;
            return pkgExpressOrderPage(params);
          }}
          tableAlertRender={false}
          columns={columns}
          options={false}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
          }}
          scroll={{ x: 750, y: 240 }}
          search={false}
        >
        </ProTable>
        <AddEditExpress
          modalVisible={addEditExpressVisible}
          onCancel={addEditExpressCancel}
          onSubmit={addEditExpressSubmit}
          itemData={itemData}
          detailData={detailData}
          type={addEditExpressType}
          ownerType={ownerType}
        ></AddEditExpress>
      </>
    </Modal>
  )
};

export default ExpressInfo;
